//
//  SKTakePhotoViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import Foundation
import UIKit
import AVFoundation
import SVProgressHUD

class SKTakePhotoViewController: UIViewController, UINavigationControllerDelegate {
    
    // MARK: - UI Components
    private let headerView = UIView()
    private let titleLabel = UILabel()
    private let backButton = UIButton(type: .system)
    private let albumButton = UIButton(type: .system)
    
    private let cameraView = UIView()
    private let previewLayer = AVCaptureVideoPreviewLayer()
    
    private let scanFrameView = UIView()
    private let instructionLabel = UILabel()
    
    private let bottomView = UIView()
    private let captureButton = UIButton(type: .system)
    
    // MARK: - Camera Properties
    private var captureSession: AVCaptureSession!
    private var stillImageOutput: AVCapturePhotoOutput!
    private var capturedImage: UIImage?
    
    // MARK: - Data
    var srcText: String?
    var dissmissViewController: ((String) -> ())?
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupCamera()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 隐藏系统导航栏和底部tab栏
        navigationController?.setNavigationBarHidden(true, animated: false)
        tabBarController?.tabBar.isHidden = true
        startCameraSession()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 显示系统导航栏和底部tab栏
        navigationController?.setNavigationBarHidden(false, animated: false)
        tabBarController?.tabBar.isHidden = false
        stopCameraSession()
        
        // 只有在有识别文字时才调用回调
        if let text = srcText, !text.isEmpty, dissmissViewController != nil {
            self.dissmissViewController!(text)
        }
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        view.backgroundColor = .black
        
        setupHeaderView()
        setupCameraView()
        setupBottomView()
    }
    
    private func setupHeaderView() {
        titleLabel.text = "OCR识别"
        titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        titleLabel.textColor = .white
        titleLabel.textAlignment = .center
        
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        backButton.tintColor = .white
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        
        albumButton.setImage(UIImage(systemName: "photo.on.rectangle"), for: .normal)
        albumButton.tintColor = .white
        albumButton.addTarget(self, action: #selector(albumButtonTapped), for: .touchUpInside)
        
        headerView.backgroundColor = UIColor.clear
        headerView.layer.cornerRadius = 12
    }
    
    private func setupCameraView() {
        cameraView.backgroundColor = .black
        
        // 扫描框
        scanFrameView.backgroundColor = .clear
        scanFrameView.layer.borderWidth = 2
        scanFrameView.layer.borderColor = UIColor.white.cgColor
        scanFrameView.layer.cornerRadius = 8
        
        // 说明文字
        instructionLabel.text = "将文字放入框内进行识别"
        instructionLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        instructionLabel.textColor = .white
        instructionLabel.textAlignment = .center
        instructionLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        instructionLabel.layer.cornerRadius = 8
        instructionLabel.layer.masksToBounds = true
    }
    
    private func setupBottomView() {
        bottomView.backgroundColor = UIColor.clear
        
        // 拍照按钮
        captureButton.backgroundColor = UIColor.systemBlue
        captureButton.layer.cornerRadius = 25
        captureButton.layer.shadowColor = UIColor.black.cgColor
        captureButton.layer.shadowOpacity = 0.2
        captureButton.layer.shadowOffset = CGSize(width: 0, height: 2)
        captureButton.layer.shadowRadius = 4
        
        captureButton.setImage(UIImage(systemName: "camera.fill"), for: .normal)
        captureButton.tintColor = .white
        captureButton.addTarget(self, action: #selector(capturePhotoTapped), for: .touchUpInside)
    }
    
    // MARK: - Camera Setup
    private func setupCamera() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .photo
        
        guard let backCamera = AVCaptureDevice.default(for: .video) else {
            showCameraErrorAlert()
            return
        }
        
        do {
            let input = try AVCaptureDeviceInput(device: backCamera)
            stillImageOutput = AVCapturePhotoOutput()
            
            if captureSession.canAddInput(input) && captureSession.canAddOutput(stillImageOutput) {
                captureSession.addInput(input)
                captureSession.addOutput(stillImageOutput)
                setupPreviewLayer()
            }
        } catch {
            showCameraErrorAlert()
        }
    }
    
    private func setupPreviewLayer() {
        previewLayer.session = captureSession
        previewLayer.videoGravity = .resizeAspectFill
        previewLayer.connection?.videoOrientation = .portrait
        cameraView.layer.addSublayer(previewLayer)
        
        // 立即设置frame
        DispatchQueue.main.async {
            self.previewLayer.frame = self.cameraView.bounds
        }
    }
    
    private func startCameraSession() {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.captureSession?.startRunning()
            DispatchQueue.main.async {
                self?.previewLayer.frame = self?.cameraView.bounds ?? .zero
            }
        }
    }
    
    private func stopCameraSession() {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            self?.captureSession?.stopRunning()
        }
    }
    
    // MARK: - Layout
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 设置约束
        setupConstraints()
        
        // 设置预览层frame
        DispatchQueue.main.async {
            self.previewLayer.frame = self.cameraView.bounds
        }
    }
    
    private func setupConstraints() {
        // 移除之前的约束
        view.subviews.forEach { $0.removeFromSuperview() }
        
        // 添加子视图
        view.addSubview(cameraView)
        cameraView.addSubview(scanFrameView)
        cameraView.addSubview(instructionLabel)
        
        view.addSubview(headerView)
        headerView.addSubview(titleLabel)
        headerView.addSubview(backButton)
        headerView.addSubview(albumButton)
        
        view.addSubview(bottomView)
        bottomView.addSubview(captureButton)
        
        // 设置frame
        let headerHeight: CGFloat = 60
        let bottomHeight: CGFloat = 120
        let safeTop = view.safeAreaInsets.top
        
        headerView.frame = CGRect(x: 20, y: safeTop + 10, width: view.bounds.width - 40, height: headerHeight)
        
        cameraView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
        
        let scanFrameWidth: CGFloat = cameraView.bounds.width * 0.8
        let scanFrameHeight: CGFloat = cameraView.bounds.height * 0.55
        let scanFrameX = (cameraView.bounds.width - scanFrameWidth) / 2
        let scanFrameY = (cameraView.bounds.height - scanFrameHeight) / 2
        scanFrameView.frame = CGRect(x: scanFrameX, y: scanFrameY, width: scanFrameWidth, height: scanFrameHeight)
        
        // 调整说明文字位置，确保在扫描框下方
        instructionLabel.frame = CGRect(x: 20, y: scanFrameY + scanFrameHeight + 10, width: cameraView.bounds.width - 40, height: 40)
        
        bottomView.frame = CGRect(x: 0, y: view.bounds.height - bottomHeight - view.safeAreaInsets.bottom, width: view.bounds.width, height: bottomHeight)
        
        captureButton.frame = CGRect(x: (bottomView.bounds.width - 50) / 2, y: (bottomView.bounds.height - 50) / 2, width: 50, height: 50)
        
        backButton.frame = CGRect(x: 16, y: (headerHeight - 44) / 2, width: 44, height: 44)
        titleLabel.frame = CGRect(x: 60, y: 0, width: headerView.bounds.width - 120, height: headerHeight)
        albumButton.frame = CGRect(x: headerView.bounds.width - 60, y: (headerHeight - 44) / 2, width: 44, height: 44)
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func albumButtonTapped() {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        present(imagePickerController, animated: true)
    }
    
    @objc private func capturePhotoTapped() {
        let photoSettings = AVCapturePhotoSettings()
        stillImageOutput.capturePhoto(with: photoSettings, delegate: self)
    }
    
    // MARK: - Helper Methods
    private func showCameraErrorAlert() {
        let alert = UIAlertController(title: "相机访问失败", message: "无法访问相机，请检查相机权限设置", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default) { _ in
            self.navigationController?.popViewController(animated: true)
        })
        present(alert, animated: true)
    }
    
    private func showFullScreenImage(_ image: UIImage) {
        let fullScreenVC = FullScreenImageViewController(image: image)
        fullScreenVC.modalPresentationStyle = .fullScreen
        present(fullScreenVC, animated: true)
    }
}

// MARK: - AVCapturePhotoCaptureDelegate
extension SKTakePhotoViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
            capturedImage = image
            DispatchQueue.main.async {
                self.showFullScreenImage(image)
            }
            self.processImage(image)
        }
    }
}

// MARK: - UIImagePickerControllerDelegate
extension SKTakePhotoViewController: UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let selectedImage = info[.originalImage] as? UIImage {
                self.processImage(selectedImage)
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

// MARK: - Image Processing
extension SKTakePhotoViewController {
    private func processImage(_ image: UIImage) {
        SVProgressHUD.show(withStatus: "正在识别...")
        
        guard let base64String = SKUitilTool.default.convertImageToBase64(image) else {
            SVProgressHUD.showError(withStatus: "图片处理失败")
            return
        }
        
        SKAFNetWork().photoToText(imageBase64: base64String) { [weak self] dic in
            guard let self = self else { return }
            
            guard let words_result = dic["words_result"] as? Array<Any> else {
                DispatchQueue.main.async {
                    SVProgressHUD.showError(withStatus: "识别失败：未找到文字")
                }
                return
            }
            
            var text = ""
            for i in 0..<words_result.count {
                guard let dictWords = words_result[i] as? Dictionary<String, Any> else { continue }
                guard let wordstr = dictWords["words"] as? String else { continue }
                if i > 0 {
                    text += "\n"
                }
                text += wordstr
            }
            
            // 保存到历史记录
            HistoryRecordManager.shared.addOCRRecord(content: text, image: image)
            
            DispatchQueue.main.async {
                SVProgressHUD.dismiss()
                self.showTextEditViewController(with: text)
            }
            
        } errorMsgHandler: { errorMsg in
            DispatchQueue.main.async {
                SVProgressHUD.showError(withStatus: "识别失败: \(errorMsg)")
            }
        } networkFailHandler: { error in
            DispatchQueue.main.async {
                SVProgressHUD.showError(withStatus: "网络错误: \(error.localizedDescription)")
            }
        }
    }
    
    private func showTextEditViewController(with text: String) {
        let alert = UIAlertController(title: "识别结果", message: text, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "复制", style: .default) { _ in
            UIPasteboard.general.string = text
            SVProgressHUD.showSuccess(withStatus: "已复制到剪贴板")
        })
        alert.addAction(UIAlertAction(title: "确定", style: .default) { _ in
            self.srcText = text
        })
        present(alert, animated: true)
    }
} 
